//
//  UITextView+Lc.m
//  18Birdies
//
//  Created by Lc on 15/5/6.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "LcFont.h"
#import "LcPreconditions.h"
#import "NSAttributedString+Lc.h"
#import "UIColor+Lc.h"
#import "UITextView+Lc.h"

@implementation UITextView (Lc)

+ (void)load {
  SEL loadAdapter = NSSelectorFromString(@"loadAdapter");
  if ([self respondsToSelector:loadAdapter]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:loadAdapter];
#pragma clang diagnostic pop
  }
}

- (void)setLcFont:(LcFont*)lcFont {
  self.font = lcFont.font;
  self.textColor = lcFont.color;
}

- (void)setString:(NSString*)string
         withUrls:(NSArray*)urlStrings
    forSubstrings:(NSArray*)substrings
           lcFont:(LcFont*)lcFont
         urlColor:(UIColor*)urlColor {
  LC_CHECK_NOT_EMPTY(string);
  LC_CHECK_NOT_EMPTY(urlStrings);
  LC_CHECK_NOT_EMPTY(substrings);
  LC_CHECK_TRUE(urlStrings.count == substrings.count);
  NSMutableAttributedString* attributedString =
      (NSMutableAttributedString*)[NSMutableAttributedString
          attributedStringWithString:string
                              lcFont:lcFont];
  for (int i = 0; i < urlStrings.count; ++i) {
    NSString* urlString = urlStrings[i];
    NSString* substring = substrings[i];
    NSRange range = [string rangeOfString:substring];
    LC_CHECK_TRUE(range.length > 0);
    [attributedString addAttribute:NSLinkAttributeName
                             value:urlString
                             range:range];
  }
  NSDictionary* linkAttributes = @{
    NSForegroundColorAttributeName : urlColor,
    NSUnderlineColorAttributeName : urlColor,
    NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)
  };
  self.linkTextAttributes = linkAttributes;
  self.attributedText = attributedString;
}

- (BOOL)needCheckInputingLanguage {
  BOOL needCheck = NO;
  if ([self.textInputMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
    if (self.markedTextRange == nil) {
      needCheck = YES;
    }
  } else {
    needCheck = YES;
  }
  return needCheck;
}

@end
